package com.simon.hse.activity.danger;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.simon.hse.MyApplication;
import com.simon.hse.R;
import com.simon.hse.activity.BaseActivity;
import com.simon.hse.adapter.CommonEmptyAdapter;
import com.simon.hse.adapter.CommonViewHolder;
import com.simon.hse.http.CommonCallBack;
import com.simon.hse.http.HttpManager;
import com.simon.hse.http.entity.DangerEliminateOutput;
import com.simon.hse.http.entity.DropDownOutput;
import com.simon.hse.http.entity.PlanCheckGetList;
import com.simon.hse.http.entity.PlanListInput;
import com.simon.hse.http.entity.PlanListOutPut;
import com.simon.hse.http.entity.TrainPersonOutput;
import com.simon.hse.interfaces.PopListener;
import com.simon.hse.utils.DateTimeUtils;
import com.simon.hse.utils.PopupWindowUtils;
import com.simon.hse.utils.ToastUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import retrofit2.Call;

/**
 * 隐患排查任务
 */
@SuppressWarnings("all")
@ContentView(R.layout.activity_detailed_investigation)
public class DangerUnvestigationActivity extends BaseActivity implements PopListener {
    @ViewInject(R.id.tv_common_title)
    TextView mTv_common_title;
    @ViewInject(R.id.iv_common_left)
    ImageView ivCommonLeft;
    @ViewInject(R.id.tv_common_title)
    TextView tvCommonTitle;
    @ViewInject(R.id.iv_common_right)
    ImageView ivCommonRight;
    @ViewInject(R.id.iv_common_right2)
    ImageView ivCommonRight2;
    @ViewInject(R.id.tv_function_1)
    TextView tvFunction1;
    @ViewInject(R.id.iv_function_1)
    ImageView ivFunction1;
    @ViewInject(R.id.ll_function_1)
    LinearLayout llFunction1;
    @ViewInject(R.id.edt_mudi)
    EditText edtMudi;
    @ViewInject(R.id.edt_content)
    EditText edtContent;
    @ViewInject(R.id.ll_law_tab)
    LinearLayout llLawTab;
    @ViewInject(R.id.recyclerview)
    RecyclerView recyclerview;
    @ViewInject(R.id.smartrefresh)
    SmartRefreshLayout smartrefresh;
    @ViewInject(R.id.tv_danger_eliminate_more_rate)
    TextView tvDangerEliminateMoreRate;
    @ViewInject(R.id.ll_danger_eliminate_more_rate)
    LinearLayout llDangerEliminateMoreRate;
    @ViewInject(R.id.tv_StartTime)
    TextView tvStartTime;
    @ViewInject(R.id.ll_StartTime)
    LinearLayout llStartTime;
    @ViewInject(R.id.tv_EndTime)
    TextView tvEndTime;
    @ViewInject(R.id.ll_EndTime)
    LinearLayout llEndTime;
    @ViewInject(R.id.tv_more_reset)
    TextView tvMoreReset;
    @ViewInject(R.id.tv_more_confirm)
    TextView tvMoreConfirm;
    @ViewInject(R.id.ll_more)
    LinearLayout llMore;
    @ViewInject(R.id.tv_confirm)
    TextView tvConfirm;
    @ViewInject(R.id.tv_cancle)
    TextView tvCancle;
    private CommonEmptyAdapter mCommonEmptyAdapter;
    private int currentPage = 1, totalPage = 1;
    private boolean isShowMore = false;
    private List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mDangerDepartList = new ArrayList<>();// 部门
    private String unit;
    private int choosePos = -1;// 当前选择的承包商下标
    private  List<PlanListOutPut.DataBean.PageDataBean>  mDataBeanList = new ArrayList<>();// 隐患排查任务列表

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTv_common_title.setText("排查详细情况");

        initRecyclerView();
        initData();
        initPopData();
    }

    @Event(value = {R.id.iv_common_left, R.id.ll_eliminate_more, R.id.ll_danger_eliminate_more_rate, R.id.ll_function_1, R.id.iv_common_right, R.id.tv_confirm, R.id.tv_cancel})
    private void clickButton(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
            case R.id.iv_common_left:
                finish();
                break;
            case R.id.ll_eliminate_more:
                break;
            case R.id.ll_function_1:
                initCommonPop(llFunction1, tvFunction1, mDangerDepartList);
                break;
            case R.id.ll_danger_eliminate_more_rate:
                break;
            case R.id.iv_common_right:
                break;
            case R.id.tv_confirm:
                if (choosePos > 0){

                }
                break;
        }
    }


    private void initRecyclerView() {
        smartrefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (currentPage * 10 < totalPage) {
                    currentPage++;
                    initData();
                } else {
                    smartrefresh.finishLoadMoreWithNoMoreData();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                
                initData();
            }
        });

        LinearLayoutManager llm = new LinearLayoutManager(DangerUnvestigationActivity.this);
        recyclerview.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        recyclerview.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        recyclerview.setItemAnimator(new DefaultItemAnimator());
        recyclerview.setNestedScrollingEnabled(false);

        mCommonEmptyAdapter = new CommonEmptyAdapter(DangerUnvestigationActivity.this, R.layout.layout_item_slect_plan, mDataBeanList);
        mCommonEmptyAdapter.setItemDatasListener(new CommonEmptyAdapter.ItemDatasListener<PlanListOutPut.DataBean.PageDataBean>() {
            @Override
            public void setItemDatas(CommonViewHolder holder, PlanListOutPut.DataBean.PageDataBean pageDataBean, int position) {

                TextView tvUnit = holder.getView(R.id.tv_unit);
                TextView tvAim = holder.getView(R.id.tv_aim);
                TextView tvPerson = holder.getView(R.id.tv_person);
                TextView tvActive = holder.getView(R.id.tv_active);
                TextView tvAsk = holder.getView(R.id.tv_ask);
                TextView tvContent = holder.getView(R.id.tv_content);
                CheckBox cbSlect = holder.getView(R.id.cb_select);

                tvUnit.setText(pageDataBean.getUnitName());
                tvAim.setText(pageDataBean.getObjective());
                tvPerson.setText(pageDataBean.getPersonInChargeText());
                tvActive.setText(pageDataBean.getParticipant());
                tvAsk.setText(pageDataBean.getRequirements());
                tvContent.setText(pageDataBean.getContent());

                if (choosePos == position) {
                    cbSlect.setChecked(true);
                } else {
                    cbSlect.setChecked(false);
                }

                cbSlect.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        choosePos = position;
                        mCommonEmptyAdapter.notifyDataSetChanged();
                    }
                });
            }
        });

        mCommonEmptyAdapter.setOnItemEmptyClickListener(new CommonEmptyAdapter.OnItemEmptyClickListener() {
            @Override
            public void setOnEmptyClickListener() {
                initData();
            }

            @Override
            public void setOnItemClickListener(View view, int position) {

            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        recyclerview.setAdapter(mCommonEmptyAdapter);
    }

    private void initData() {

        PlanListInput planListInput = new PlanListInput();
        PlanListInput.ModelBean modelBean = new PlanListInput.ModelBean();

        modelBean.setObjective(edtMudi.getText().toString());
        modelBean.setContent(edtContent.getText().toString());
        modelBean.setUnit(unit);

        planListInput.setModel(modelBean);
        planListInput.setLimit(10);
        planListInput.setOffset(10 * (currentPage - 1));


        Call<String> call = HttpManager.getInstance().requestService().DANGER_GET_PLAN_LIST(HttpManager.getInstance().requestBody(planListInput));
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                PlanListOutPut planListOutPut = new Gson().fromJson(result, PlanListOutPut.class);
                if (planListOutPut.getResult().equals("Success")) {
                    totalPage = planListOutPut.getData().getRowCount();
                    List<PlanListOutPut.DataBean.PageDataBean> dataBeanList = planListOutPut.getData().getPageData();
                    mDataBeanList.addAll(dataBeanList);
                    mCommonEmptyAdapter.notifyDataSetChanged();

                    smartrefresh.finishRefresh();
                    smartrefresh.finishLoadMore();
                } else {
                    ToastUtils.getInstance().showShortToastBottom("接口返回数据错误");
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * pop data
     */
    private void initPopData() {
        DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean = new DropDownOutput.DataBean.DataDicListBean.ValueBean();
        valueBean.setKey("");
        valueBean.setValue("全部");

        mDangerDepartList.add(valueBean);
        mDangerDepartList.addAll(MyApplication.getInstance().mDangerDepartList);

    }

    /**
     * 共用Pop
     */
    private void initCommonPop(LinearLayout mLl, final TextView mTv, final List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mList) {
        View inflate = LayoutInflater.from(DangerUnvestigationActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView recyclerview = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(DangerUnvestigationActivity.this);
        recyclerview.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        recyclerview.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        recyclerview.setItemAnimator(new DefaultItemAnimator());
        recyclerview.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(DangerUnvestigationActivity.this, R.layout.layout_item_common_more_department, mList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<DropDownOutput.DataBean.DataDicListBean.ValueBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, DropDownOutput.DataBean.DataDicListBean.ValueBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getValue());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {

                DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean = mList.get(position);
                mTv.setText(valueBean.getValue());
                unit = valueBean.getKey();
                PopupWindowUtils.getInstance().closePop();
                upData();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        recyclerview.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(DangerUnvestigationActivity.this, inflate, mLl);
    }


    /**
     * 公用时间选择
     */
    public void reportDate(TextView tv) {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        startDate.set(1949, 1, 1);
        String currentYMD = DateTimeUtils.getCurrentYMD();
        String[] split = currentYMD.split("-");
        selectedDate.set(Integer.parseInt(split[0]), Integer.parseInt(split[1]) - 1, Integer.parseInt(split[2]));
        endDate.set(Integer.parseInt(split[0]), Integer.parseInt(split[1]) - 1, Integer.parseInt(split[2]));

        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat sdf_ymd = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS'Z'");//设置日期格式
                tv.setText(sdf_ymd.format(date));
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .build();

        pvTime.show();
    }

    @Override
    public void upData() {
        currentPage = 1;
        mDataBeanList.clear();
        initData();
    }
}
